package provisionamento.view;

import MyExceptions.DaoException;
import Sistema.*;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import provisionamento.controller.FramesController;
import provisionamento.model.Categoria;
import provisionamento.model.GrupoUnitario;
import provisionamento.model.Mensagem;

public class FrameGrupoUnitario extends javax.swing.JFrame implements Observer {

    private FrameCategoria frameCategoria;
    private boolean fechar;
    private FramesController controller;
    private Mensagem mensagemFonte;

    public FrameGrupoUnitario() {

        initComponents();
        frameCategoria = new FrameCategoria();
        controller = new FramesController();

        try {
            cbCategoria.removeAllItems();
            List<Categoria> categorias = controller.buscaCategoria();

            for (Categoria cat : categorias) {
                cbCategoria.addItem(cat);
            }
        } catch (DaoException ex) {
            Logger.getLogger(FrameGrupoComunitario.class.getName()).log(Level.SEVERE, null, ex);
        }
        ConcreteSubject.getInstancia().registerObserver(this);
    }

    public FrameGrupoUnitario(Mensagem mensagem) {
        initComponents();
        controller = new FramesController();
        GrupoUnitario grupo = mensagem.getGrupo();
        this.mensagemFonte = mensagem;
        cbCategoria.removeAllItems();
        cbCategoria.addItem(grupo.getCategoria());
        cbCategoria.setEnabled(false);
        btAddCategoria.setEnabled(false);

        this.fechar = true;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelCategoria = new javax.swing.JLabel();
        cbCategoria = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        tfQtdItens = new javax.swing.JTextField();
        btAddCategoria = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        tfDataVencimento = new javax.swing.JTextField();
        btAddGrupoInd = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        tfQtdDias = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        btFechar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        TxtValor = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        labelCategoria.setText("Categoria:");

        cbCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbCategoriaActionPerformed(evt);
            }
        });

        jLabel1.setText("Novo Grupo");

        jLabel2.setText("Quantidade:");

        btAddCategoria.setText("+");
        btAddCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddCategoriaActionPerformed(evt);
            }
        });

        jLabel3.setText("Vencimento:");

        tfDataVencimento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfDataVencimentoActionPerformed(evt);
            }
        });

        btAddGrupoInd.setText("Adicionar Grupo");
        btAddGrupoInd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddGrupoIndActionPerformed(evt);
            }
        });

        jLabel6.setText("Notificar:");

        jLabel7.setText("dias antes do vencimento.");

        btFechar.setText("Fechar");
        btFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFecharActionPerformed(evt);
            }
        });

        jLabel4.setText("Valor:");

        TxtValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        TxtValor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TxtValorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btAddGrupoInd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btFechar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(187, 187, 187)
                        .addComponent(jLabel1)
                        .addGap(0, 193, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(labelCategoria)
                                        .addGap(19, 19, 19)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cbCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(btAddCategoria))
                                    .addComponent(tfQtdItens, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(tfQtdDias, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel7))
                                    .addComponent(tfDataVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(TxtValor, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(211, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(7, 7, 7)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelCategoria)
                    .addComponent(cbCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btAddCategoria))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tfQtdItens, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tfDataVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(tfQtdDias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(TxtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAddGrupoInd)
                    .addComponent(btFechar))
                .addGap(28, 28, 28))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbCategoriaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbCategoriaActionPerformed

    private void btAddGrupoIndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddGrupoIndActionPerformed
        try {

            int qtdItens = 0;
            int qtdAntecip = 0;
            int qtdVencimento = 0;
            boolean ok = true;
            Date prazo = new Date();

            if (tfQtdItens.getText().equals("")) {
                ok = false;
                JOptionPane.showMessageDialog(null, "Quantidade de itens deve ser informada!");
            }
            try {
                qtdItens = Integer.parseInt(tfQtdItens.getText());
            } catch (NumberFormatException ex) {
                ok = false;
                JOptionPane.showMessageDialog(null, "Quantidade de itens deve ser um número!");
            }

            if (tfDataVencimento.getText().equals("")) {
                ok = false;
                JOptionPane.showMessageDialog(null, "Prazo de validade deve ser informado!");
            }
            try {
                qtdVencimento = Integer.parseInt(tfDataVencimento.getText());
            } catch (NumberFormatException ex) {
                ok = false;
                JOptionPane.showMessageDialog(null, "Prazo de validade deve ser um número!");
            }

            if (tfQtdDias.getText().equals("")) {
                qtdAntecip = 0;
            } else {
                try {
                    qtdAntecip = Integer.parseInt(tfQtdDias.getText());
                } catch (NumberFormatException ex) {
                    ok = false;
                    JOptionPane.showMessageDialog(null, "Dias para notificar deve ser um número!");
                }
            }
            if (ok == true) {
                prazo.setTime(prazo.getTime() + ((24 * 3600000) * qtdVencimento));

                GrupoUnitario grupoUnitario = new GrupoUnitario();
                grupoUnitario.setCategoria((Categoria) cbCategoria.getSelectedItem());
                grupoUnitario.setQrdDiasNotificacao(qtdAntecip);
                grupoUnitario.setQuantidade(qtdItens);
                grupoUnitario.setPrazoValidade(prazo);
                grupoUnitario.setValorCompra(Double.parseDouble(TxtValor.getText().replace(',', '.')));
                grupoUnitario.setCriador(Session.getInstancia().getUsuarioLogado());

                controller.grava(grupoUnitario);
                if (mensagemFonte != null) {
                    mensagemFonte.getGrupo().setFinalizado(true);
                    controller.notificar(mensagemFonte);
                    controller.notificar(mensagemFonte.getGrupo());
                }

                JOptionPane.showMessageDialog(null, "Grupo cadastrado com sucesso!");

                if (this.fechar == true) {
                    ConcreteSubject.getInstancia().removeOberser(this);
                    this.dispose();
                }

                tfDataVencimento.setText(null);
                tfQtdDias.setText(null);
                tfQtdItens.setText(null);
                TxtValor.setText(null);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }//GEN-LAST:event_btAddGrupoIndActionPerformed

    private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFecharActionPerformed
        ConcreteSubject.getInstancia().removeOberser(this);
        this.dispose();
    }//GEN-LAST:event_btFecharActionPerformed

    private void btAddCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddCategoriaActionPerformed
        // TODO add your handling code here:
        frameCategoria.setVisible(true);
    }//GEN-LAST:event_btAddCategoriaActionPerformed

    private void tfDataVencimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfDataVencimentoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfDataVencimentoActionPerformed

    private void TxtValorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtValorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_TxtValorActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField TxtValor;
    private javax.swing.JButton btAddCategoria;
    private javax.swing.JButton btAddGrupoInd;
    private javax.swing.JButton btFechar;
    private javax.swing.JComboBox cbCategoria;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel labelCategoria;
    private javax.swing.JTextField tfDataVencimento;
    private javax.swing.JTextField tfQtdDias;
    private javax.swing.JTextField tfQtdItens;
    // End of variables declaration//GEN-END:variables

    @Override
    public void update(Object obj) {
        if (obj instanceof Categoria) {
            cbCategoria.addItem((Categoria) obj);
        }
    }
}
